﻿using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Xml;
using Pdf2epub.BusinessLogic;
using Pdf2epub.BusinessLogic.Extractors;
using Pdf2epub.Interfaces;
using Pdf2epub.Model;

namespace Pdf2epub.UI
{
    /// <summary>
    /// Interaction logic for TableDetectionConfigurator.xaml
    /// </summary>
    public partial class TableDetectionConfigurator : Window
    {
        public IProjectContext ProjectContext { get; set; }

        public TableDetectionConfigurator(IProjectContext context)
        {
            ProjectContext = context;

            InitializeComponent();
        }

        private void RenderPageCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = (nuPageToPreview.Value != null) &&  (ProjectContext.ProjectConfiguration.NumberOfPages > 0);
        }

        private void OnCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command is RoutedUICommand)
            {
                RoutedUICommand uiCommand = e.Command as RoutedUICommand;
                switch (uiCommand.Name)
                {
                    case "RenderPage":
                        RenderPage();
                        break;
                }
            }
        }

        private void RenderPage()
        {
            if (nuPageToPreview.Value == null)
                return;

            int page = (int) nuPageToPreview.Value;

            string tempFolder = CreateTempDirectory();

            PdfHtmlExtractor extractor = ExtractorFactory.GetExtractor(ProjectContext, ProjectContext.ProjectConfiguration.PdfPath, tempFolder) as PdfHtmlExtractor;
            if (extractor == null)
                return;

            HtmlRenderEngine renderEngine = new HtmlRenderEngine(ProjectContext);
            XmlDocument htmlDoc = renderEngine.RenderHtmlFromContentBlocks(extractor.ExtractPage(page));

            webBrowser.NavigateToString(htmlDoc.InnerXml);

            Directory.Delete(tempFolder, true);
        }

        private static string CreateTempDirectory()
        {
            string folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            while (Directory.Exists(folder) || File.Exists(folder))
            {
                folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            }
            Directory.CreateDirectory(folder);

            return folder;
        }
    }
}
